package authentification;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AuthentificationServlet
 */
public class AuthentificationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AuthentificationServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().write("Hello, world 2!");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String login = request.getParameter("login");
		String pwd = request.getParameter("pwd");		
		
		try {
			String requete = "SELECT PASSWORD FROM UTILISATEUR WHERE LOGIN LIKE '#'";
			requete = requete.replace("#", login);
			ResultSet resultSet = BDConnexion.getConnection().createStatement().executeQuery(requete);			
			
			String password="";
			while(resultSet.next()){
				password = resultSet.getString("PASSWORD");
				break;
			}
			
			if(password.equals(pwd)){
				request.getSession().setAttribute("login", login);
				request.getRequestDispatcher("accueil.jsp").forward(request, response);
			}else{
				request.getRequestDispatcher("index.jsp").forward(request, response);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
